import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import Layout from '@/layouts/MainLayout.vue'
// import Layout from '@/layouts/index.vue'


// 静态路由
const constantRoutes = [
  {
    path: '/login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    component: () => import('../layouts/MainLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'PieChartOutlined' }
      }
    ]
  },
  {
    path: "/vuejs",
    name: "vuejsIndex",
    component: Layout,
    // meta: { title: "vuejsIndex", hidden: false },
    children: [
      {
        path: "/vuejs/:page*",
        component: () => import("@/views/vuejs/index.vue"),
        meta: { keepAlive: true },
        name: "vuejs"
      }
    ]
  },
  {
    path: "/reactjs",
    name: "reactjsIndex",
    component: Layout,
    // meta: { title: "reactjsIndex", hidden: false },
    children: [
      {
        path: "/reactjs/:page*",
        component: () => import("@/views/reactjs/index.vue"),
        meta: { keepAlive: true },
        name: "reactjs"
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

// 动态路由加载
router.beforeEach(async (to) => {
  const authStore = useAuthStore()
  
  // 已登录访问登录页
  if (to.path === '/login' && authStore.token) return '/'
  
  // 需要认证的页面
  if (!authStore.token && to.path !== '/login') {
    return '/login'
  }
  
  // 加载动态路由
  if (authStore.token && !authStore.hasRoutes) {
    await authStore.getMenu()
    authStore.menuRoutes.forEach(route => {
      router.addRoute('MainLayout', {
        path: route.path,
        component: () => import('../layouts/MainLayout.vue'),
        children: route.children?.map(child => ({
          path: child.path,
          component: () => import(`../views/${child.component}.vue`),
          meta: child.meta
        })) || []
      })
    })
    authStore.hasRoutes = true
    return to.fullPath
  }
})

export default router